﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;

namespace Kurax.BoardGames.Client.Web {
    public partial class Default : Page {
        protected const string AUTH_COOKIE_NAME = "AUTH";

        private string GetAuthString(string id, string email) {
            var array = Encoding.UTF8.GetBytes(email);
            Array.Reverse(array);
            return string.Format("{0}:{1}", email, Convert.ToBase64String((new Crypto()).Encrypt(Encoding.UTF8.GetBytes(id), (MD5.Create()).ComputeHash(array))));
        }

        protected void Page_Load(object sender, EventArgs e) {
            var ns = this.Request["openid.ns"];
            if(string.IsNullOrEmpty(ns)) {
                var cookie = this.Request.Cookies[AUTH_COOKIE_NAME];
                if(cookie != null) {
                    cookie.Expires = DateTime.Now.AddDays(3);
                    this.Response.SetCookie(cookie);
                }
            } else {
                var mode = this.Request["openid.mode"];
                HttpCookie cookie;
                switch(mode) {
                    case "id_res":
                        var auth = this.GetAuthString(this.Request["openid.identity"], this.Request["openid.ext1.value.email"]);
                        cookie = new HttpCookie(AUTH_COOKIE_NAME, auth) {
                            Expires = DateTime.Now.AddDays(3),
                        };
                        this.Response.SetCookie(cookie);
                        break;
                    case "cancel":
                    case "error":
                        cookie = this.Request.Cookies[AUTH_COOKIE_NAME];
                        if(cookie != null) {
                            cookie.Expires = DateTime.Now;
                            this.Response.SetCookie(cookie);
                        }
                        break;
                }
                this.Response.Redirect("/");
            }
        }

        protected string GetInitParams() {
            var cookie = this.Request.Cookies[AUTH_COOKIE_NAME];
            return cookie != null ? "auth=" + cookie.Value : string.Empty;
        }
    }
}
